using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using NLog;

namespace LDNS.Services
{
    /// <summary>
    /// Windows 服务托管类，负责在 SCM 管理下启动和停止 LDNS 服务
    /// 作者：huobing
    /// </summary>
    public class WindowsDnsHostedService : IHostedService
    {
        private readonly DnsServiceManager _manager;
        private readonly DnsServiceOptions _options;
        private Task? _runTask;
        private CancellationTokenSource? _cts;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 构造函数，注入服务管理器与启动选项
        /// </summary>
        /// <param name="manager">DNS服务管理器</param>
        /// <param name="options">启动选项</param>
        public WindowsDnsHostedService(DnsServiceManager manager, DnsServiceOptions options)
        {
            _manager = manager;
            _options = options ?? new DnsServiceOptions();
            _options.IsService = true; // 明确标记为服务模式
        }

        /// <summary>
        /// 当服务被 SCM 启动时执行，启动 LDNS 主服务
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>异步任务</returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.Info("服务任务启动中……");
            
            try
            {
                _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                _logger.Debug("已创建取消令牌源");
                
                _runTask = Task.Run(() =>
                {
                    try
                    {
                        _logger.Debug("准备调用 DnsServiceManager.Run() 方法启动核心DNS服务");
                        _manager.Run(_options);
                        _logger.Debug("DnsServiceManager.Run() 方法调用完成");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex, "服务任务启动异常");
                        // 发生异常时由宿主框架处理并记录
                    }
                }, _cts.Token);
                
                _logger.Info("服务任务已启动");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "服务任务启动时发生异常");
            }
            
            return Task.CompletedTask;
        }

        /// <summary>
        /// 当服务被 SCM 停止时执行，停止 LDNS 主服务
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>异步任务</returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.Info("WindowsDnsHostedService.StopAsync 开始执行");
            
            try
            {
                _logger.Debug("正在取消服务任务");
                _cts?.Cancel();
                _logger.Info("正在调用 DnsServiceManager.StopService() 方法停止核心DNS服务");
                _manager.StopService();
                _logger.Info("核心DNS服务已停止");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "停止服务过程中发生异常");
                // 停止异常忽略，由宿主框架处理
            }
            
            return Task.CompletedTask;
        }
    }
}